package com.feihong.yw189.paidan.qiangdanservice;

import android.Manifest;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.feihong.yw189.R;
import com.feihong.yw189.bluetooth.utils.util.PrefUtils;
import com.feihong.yw189.paidan.qiangdanservice.newversion.PaiDanRemoteService;


/**
 * Created by Sabirjan on 2017/6/15.
 * TXGW.
 * 飞宏电子
 */

public class LocationToolsOnces implements AMapLocationListener {

    private static final int NOTICATION_ID = 10301;
    private static final int TIME = 2000;
    private static final String TAG = "派单";
    /**
     * 需要进行检测的权限数组
     */
    protected String[] needPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE
    };
    //声明mLocationOption对象
    private AMapLocationClientOption mLocationOption = null;
    private AMapLocationClient mlocationClient = null;
    private LocationCallBack callBack;
    private Context mContext;
    private LocationInfo locationInfo = new LocationInfo();

    public LocationToolsOnces(Context context, LocationCallBack callBack) throws NullPointerException {

        mContext = context;
        this.callBack = callBack;
        if (mContext == null) {
            if (callBack == null) {
                throw new NullPointerException("Context is NULL");
            }
            callBack.error("Context is NULL");
            return;
        }
        checkPermission();

    }

    private void checkPermission() {

    }

    public void stopLocation() {
        try {

            if (mlocationClient != null) {
                //关闭后台定位，参数为true时会移除通知栏，为false时不会移除通知栏，但是可以手动移除
                mlocationClient.disableBackgroundLocation(true);
                mlocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
                mlocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
            }
            mlocationClient = null;
         //   this.callBack = null;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void startLocation(final int sellep) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (sellep > 0) {
                    try {
                        Thread.sleep(sellep);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                init();

            }
        }).start();

    }

    private void init() {
        locationInfo = new LocationInfo();
        mlocationClient = new AMapLocationClient(mContext);
//初始化定位参数
        mLocationOption = new AMapLocationClientOption();
//设置返回地址信息，默认为true
        mLocationOption.setNeedAddress(false);
//设置定位监听
        mlocationClient.setLocationListener(this);
//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(15000);
        //启动后台定位，第一个参数为通知栏ID，建议整个APP使用一个
        //mlocationClient.enableBackgroundLocation(NOTICATION_ID, buildNotification());
        //   mLocationOption.setKillProcess(true);
      //  mLocationOption.setGpsFirst(true);
        mLocationOption.setLocationCacheEnable(true);
        mLocationOption.setOnceLocation(true);//获取一次定位结果：
        mLocationOption.setOnceLocationLatest(true);//获取最近3s内精度最高的一次定位结果：
//设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
// 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
// 在定位结束后，在合适的生命周期调用onDestroy()方法
// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
//启动定位
        if (!mlocationClient.isStarted())
            mlocationClient.stopLocation();
            mlocationClient.startLocation();

    }


    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                Log.i(TAG, "onLocationChanged: 定位成功回调信息，设置相关消息");
                locationInfo.setAccuracy(amapLocation.getAccuracy());
                //   locationInfo.setAdCode(amapLocation.getAdCode());
                //  locationInfo.setAddress(amapLocation.getAddress());
                //   locationInfo.setCity(amapLocation.getCity());
                //   locationInfo.setCityCode(amapLocation.getCityCode());
                //   locationInfo.setCountry(amapLocation.getCountry());
                // locationInfo.setDatetime(amapLocation.getTime());
                //    locationInfo.setDistrict(amapLocation.getDistrict());
                locationInfo.setLatitude(amapLocation.getLatitude());
                locationInfo.setLongitude(amapLocation.getLongitude());
                // locationInfo.setProvince(amapLocation.getProvince());

                //  locationInfo.setStreet(amapLocation.getStreet());
                //   locationInfo.setStreetNum(amapLocation.getStreetNum());
                mHandler.sendEmptyMessage(1);
//                amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
//                amapLocation.getLatitude();//获取纬度
//                amapLocation.getLongitude();//获取经度
//                amapLocation.getAccuracy();//获取精度信息
//                amapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
//                amapLocation.getCountry();//国家信息
//                amapLocation.getProvince();//省信息
//                amapLocation.getCity();//城市信息
//                amapLocation.getDistrict();//城区信息
//                amapLocation.getStreet();//街道信息
//                amapLocation.getStreetNum();//街道门牌号信息
//                amapLocation.getCityCode();//城市编码
//                amapLocation.getAdCode();//地区编码

            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());
                String error = amapLocation.getErrorInfo() + " errorCode:" + amapLocation.getErrorCode();
                Message message = new Message();
                message.what = -1;
                message.obj = amapLocation.getErrorCode();
                mHandler.sendMessage(message);

            }
        }
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                PrefUtils.setString(mContext, PaiDanRemoteService.PaiDanLongitude, locationInfo.getLongitude() + "");
                PrefUtils.setString(mContext, PaiDanRemoteService.PaiDanLatitude, locationInfo.getLatitude() + "");
                PrefUtils.setString(mContext, PaiDanRemoteService.LAST_LOC_TIME, System.currentTimeMillis() + "");
                Log.i(TAG, "handleMessage: 保存了最新的位置信息.....");
                if (callBack != null) {

                    callBack.successGetLocation(locationInfo);

                }
            } else {

                if (callBack != null) {
                    callBack.error(msg.obj.toString());
                }
            }
            stopLocation();

        }
    };

    private static final String NOTIFICATION_CHANNEL_NAME = "BackgroundLocation";
    private NotificationManager notificationManager = null;
    boolean isCreateChannel = false;

    private Notification buildNotification() {

        Notification.Builder builder = null;
        Notification notification = null;
        if (null == notificationManager) {
            notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        }
        builder = new Notification.Builder(mContext);
        builder.setSmallIcon(R.mipmap.icon)
                .setContentTitle("营维189")
                .setContentText("正在后台运行")
                .setWhen(System.currentTimeMillis());
        notification = builder.build();
        return notification;
    }
}
